// manager/pages/otherreporting/index.js
import { request } from '../../../utils/request';
import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
import validateIdent from '../../../common/validateIdent';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        disabled: false,
        userInfo: {},
        busiList: [],
        dict: {},
        startDate: "",
        endDate: "",
        code: "",
        form: {
            configId: "",
            othCustName: "",
            othCustPhone: "",
            othCustIdcard: "",
            othPrdType: "",   // 产品类型 ecard_busi_oth_prd_type
            othAmount: "",   // 金额
            perMarketingDate: "",   // 营销日期
            creatorId: "",
            deptId: "",
            userCode: "",
            remark: "",
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            startDate: util.getDateMonthFrist(),
            endDate: util.formatDate(new Date()),
            code: options.code,
            "form.configId": options.id,
            "form.perMarketingDate": util.formatDate(new Date()),
        })
        wx.setNavigationBarTitle({
            title: options.name 
        })
        if(options.code == "busi_oth_living_expenses"){
            // 生活缴费产品类型
            this.getDictionaryInfo("ecard_busi_oth_living_expenses");
        }else{
            // 贵金属业务产品类型
            this.getDictionaryInfo("ecard_busi_oth_prd_type");
        }
        // 贵金属业务
        this.initValidate(["othCustName","othCustPhone","othCustIdcard","othPrdType","othAmount","perMarketingDate"]);
        if(options.detailId){
            this.setData({
                disabled: true
            })
            this.getMyBusiReportDetail(options);
        }
        this.getUserInfo();
        this.getReportConfigList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    // 用户信息
    getUserInfo(e) {   
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                form.creatorId = res.data.userInfo.registId;
                form.deptId = res.data.userInfo.deptId;
                form.userCode = res.data.userInfo.userCode;
                this.setData({
                    userInfo: res.data.userInfo,
                    form
                }) 
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    // 获取详情
    getMyBusiReportDetail(params) {   
        request({
            url: "/busi/reportConfig/getMyBusiReportDetail",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                busiType: params.busiType,
                id: params.detailId,
                configId: params.id,
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                form = Object.assign(form, res.data);
                form.othCustIdcard = form.othCustIdcard&&util.formatCardNum(form.othCustIdcard);
                this.setData({
                    form
                }) 
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    /**
     * 获取字典
     */
    getReportConfigList() {
        request({
            url: "/busi/reportConfig/getReportConfigList",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
				dictType: "ecard_business_reporting_sort",
				busiType: 4
			}
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    busiList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })     
    },
    /**
     * 获取字典
     */
    getDictionaryInfo(dictType) {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    ['dict.'+dictType]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        this.setData({
            ['form.'+key]: value
        })
    },
    /**
     * 日期选择
     */
    bindDateChange: function(e) {
        let { key } = e.currentTarget.dataset;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },
    // 保存
    save(){
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        let { form } = this.data;
        request({
            url: "/busi/reportOther/addReportOtherInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });                
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate(keys) {
        // 验证字段的规则
        const allRules = {
            othCustName: {
                required: true,
                name: true
            },
            othCustPhone: {
                required: true,
                tel: true
            },
            othCustIdcard: {
                required: true,
                cardNo: true,
                checkProvince: true,
                checkBirthday: true,
                checkParity: true,
            },
            othPrdType: {
                required: true,
            },
            othAmount: {
                required: true,
                amount: true
            },
            perMarketingDate: {
                required: true,
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const allMessages = {
            othCustName: {
                required: '请输入客户姓名',
            },
            othCustPhone: {
                required: '请输入联系方式',
                tel: '请输入正确的联系方式'
            },
            othCustIdcard: {
                required: '请输入身份证号',
                // idcard: '请输入正确的身份证号'
            },
            othPrdType: {
                required: '请选择产品类型',
            },
            othAmount: {
                required: '请输入金额',
            },
            perMarketingDate: {
                required: '请选择营销日期'
            },
        }

        let rules = {}; 
        let messages = {};
        keys.forEach(key => {
            rules[key] = allRules[key];
            messages[key] = allMessages[key];
        })

        this.WxValidate = new WxValidate(rules, messages)
        // 自定义验证规则
        this.WxValidate.addMethod('name', (value, param) => {
            var returnVal = true;
            if(/^[\u4e00-\u9fa5]{2,6}$/.test(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '客户名称为2-6个中文')
        // 自定义验证规则
        this.WxValidate.addMethod('cardNo', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_isCardNo(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '请输入18位身份证号')
        this.WxValidate.addMethod('checkProvince', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkProvince(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号省份不正确')
        this.WxValidate.addMethod('checkBirthday', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkBirthday(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号出生日期不正确')
        this.WxValidate.addMethod('checkParity', (value, param) => {
            var returnVal = true;
            if(validateIdent.IdentityCode_checkParity(value)){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '身份证号检验位不正确')
        // 自定义验证规则
        this.WxValidate.addMethod('amount', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '金额为大于0数字或保留2位的小数')
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})